<?php
/**
 * @Date: 2018-6-11
 * @Time: 16:27
 * @Author: wangxuejiao
 */
namespace app\api\controller;

use app\admin\model\ApiResponse;
use app\common\controller\Base;
use app\common\controller\SinaHq;
use app\common\model\UserStock;


class SelfSelectStock extends Base
{
    public function index(){
        $form = $this->getAndCheckForm([
            ['page', 'integer', '参数类型不正确',],
            ['rows', 'integer', '参数类型不正确'],
        ]);
        $form['page'] = $form['page'] ?? 1;
        $form['rows'] = $form['rows'] ?? 20;

        $user_id = checkUserToken(true);
        $data=UserStock::getPaginate($user_id,'stock_code',$form['rows']);
        $stocks=array_column($data['data'],'stock_code');
        $stocks_info=SinaHq::getStock($stocks);
        $return=SinaHq::changeData($stocks_info);

        return ApiResponse::success($return);
    }

    public function add(){
        list($form,$user_id)=$this->chechForm();
        $data=[
            'stock_code'=>$form['stock_code'],
            'user_id'=> $user_id,
        ];
        $stock=UserStock::findOne($data);
        if($stock) return ApiResponse::error(ApiResponse::ERR_EXISTS,'该股已为您的自选股，请勿重复添加');

        $model=new UserStock();
        $data['create_time']=time();
        $res=$model->data($data)->save();
        return $res ?  ApiResponse::success($res) :  ApiResponse::error(ApiResponse::ERR_SERVER,'添加失败');
    }


    public function delete(){
        $form=$this->checkId();
        $condition=['id'=>$form['id']];
        $stock=UserStock::findOne($condition);
        if(!$stock) return ApiResponse::error(ApiResponse::ERR_DATA_NULL,'数据不存在');
        $res=UserStock::remove($condition);
        return $res ?  ApiResponse::success($res) :  ApiResponse::error(ApiResponse::ERR_SERVER,'删除失败');
    }

    public function setTop(){
        $form=$this->checkId();
        $condition=['id'=>$form['id']];
        $stock=UserStock::findOne($condition);
        if(!$stock) return ApiResponse::error(ApiResponse::ERR_DATA_NULL,'数据不存在');
        $max_sort=UserStock::maxSort();
        $stock->sort=$max_sort+1;
        $res=$stock->save();
        return $res ?  ApiResponse::success($res) :  ApiResponse::error(ApiResponse::ERR_SERVER,'置顶失败');
    }

    public function checkId(){
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
        ]);
        return $form;
    }

    public function chechForm(){
        $form = $this->getAndCheckForm([
            ['stock_code', 'require|length:8',],
            ['stock_code',['regex'=>'/^(?i)s[hz]\d{6}$/']]
        ]);

        $stocks_info=SinaHq::getStock([$form['stock_code']]);
        if(!$stocks_info[0][0]) return ApiResponse::error(ApiResponse::ERR_DATA_NULL,'股票代码错误');

        $user_id = checkUserToken(true);

        return [$form,$user_id];
    }

}